#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os,sys
sys.path.append("/Users/admin/Documents/stock/UGFAFAFA/code/")
import pandas as pd
from database import con,droptable


def select(table, fitter, orderby=[],limmit=0, offset=0, asc = True):

    sql = ("select * from %s "  % table)
    if len(fitter)>0:
        str = ("WHERE %s " % fitter)
        sql += str 
    if len(orderby)>0:
        str = ("ORDER BY %s " % ",".join(orderby))
        sql += str 

    astr = "ASC" if asc == True else "DESC "
    sql += astr 
    if limmit>0:
        str = ("LIMIT %s OFFSET %s" % (limmit,offset))
        sql += str 
     
    cur = con.cursor()
    cur.execute(sql)
    return cur.fetchall()

 
def last(table, fitter, orderby=[], asc = True):
    
    sql = ("select * from %s "  % table)
    if len(fitter)>0:
        str = ("WHERE %s " % fitter)
        sql += str 
    if len(orderby)>0:
        str = ("ORDER BY %s " % ",".join(orderby))
        sql += str 

    astr = "ASC" if asc == True else "DESC "
    sql += astr 

    cur = con.cursor()
    cur.execute(sql)
    return cur.fetchone()
   
def select_count(table,fitter) -> int:
    sql = ("""
    select count(*) as count from %s 
    """ % table)
    if len(fitter)>0:
        str = ("WHERE %s " % fitter)
        sql += str 
    cur = con.cursor()
    cur.execute(sql)
    return cur.fetchone()["count"]


# rows = select("stockdaily" ,fitter="code='000848.SZ'",orderby=["date"],limmit=1,asc=False)
# row = last("stockdaily" ,fitter="code='000848.SZ'",orderby=["date"],limmit=1,asc=False)
# print("==")